﻿using System;
using System.Data.Entity;
using System.Linq;
using System.Reflection;
using Yto.Common.Reflection;
using Yto.Common.Dependency;
using Yto.Entities;

namespace Yto.Repositories
{
    public class RegistRepositories : IRegistRepositories
    {
        private ICtnManager _ctnManager;

        public RegistRepositories(ICtnManager ctnManager)
        {
            _ctnManager = ctnManager;
        }
        public void RegistRepository(Type type, Type repsitoryType, Type secondRepsitoryType)
        {
            var types = from property in type.GetProperties(BindingFlags.Public | BindingFlags.Instance)
                        where
                             (ReflectHelper.IsAssignableFrom(property.PropertyType, typeof(IDbSet<>))
                             || ReflectHelper.IsAssignableFrom(property.PropertyType, typeof(DbSet<>)))
                             && ReflectHelper.IsAssignableFrom(property.PropertyType.GenericTypeArguments[0], typeof(IEntity<>))
                        select new { property.PropertyType, property.DeclaringType };

            foreach (var item in types)
            {
                var pkType = EntityCommon.GetGeneticPrimaryKey(item.PropertyType.GenericTypeArguments[0]);
                if (pkType == typeof(int))
                {
                    Type _IRepType = typeof(IBaseRepository<>).MakeGenericType(item.PropertyType.GenericTypeArguments[0]);
                    Type _ImplRepType = repsitoryType.MakeGenericType(item.DeclaringType, item.PropertyType.GenericTypeArguments[0]);
                    if (!_ctnManager.IsRegisted(_IRepType))
                    {
                        _ctnManager.Regist(_IRepType, _ImplRepType, RegisterLifeStyle.Transient);
                    }
                }
                else
                {
                    Type _IRepType = typeof(IBaseRepository<,>).MakeGenericType(item.PropertyType.GenericTypeArguments[0], pkType);
                    Type _ImplRepType = secondRepsitoryType.MakeGenericType(item.DeclaringType, item.PropertyType.GenericTypeArguments[0], pkType);
                    if (!_ctnManager.IsRegisted(_IRepType))
                    {
                        _ctnManager.Regist(_IRepType, _ImplRepType, RegisterLifeStyle.Transient);
                    }
                }

            }
        }
    }
}
